package org.xzx.cloud;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.xzx.cloud.permission.PermissionClient;
import org.xzx.cloud.vo.CommonResponse;
import org.xzx.cloud.vo.CreatePathRequest;
import org.xzx.cloud.vo.PermissionInfo;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限注册组件
 */
@Slf4j
public class PermissionRegistry {
    /**
     * 权限服务SDK客户端
     */
    private final PermissionClient permissionClient;

    /**
     * 服务名称
     */
    private final String serviceName;

    PermissionRegistry(PermissionClient permissionClient, String serviceName) {
        this.permissionClient = permissionClient;
        this.serviceName = serviceName;
    }

    /**
     * 权限注册
     *
     * @param infoList
     * @return
     */
    boolean register(List<PermissionInfo> infoList) {
        if (CollectionUtils.isEmpty(infoList)) {
            return false;
        }
        List<CreatePathRequest.PathInfo> pathInfos = infoList.stream()
                .map(info -> CreatePathRequest.PathInfo.builder()
                        .pathPattern(info.getUrl())
                        .httpMethod(info.getMethod())
                        .pathName(info.getDescription())
                        .serviceName(serviceName)
                        .opMode(info.getIsRead() ? OpModeEnum.READ.name() : OpModeEnum.WRITE.name())
                        .build()
                ).collect(Collectors.toList());


        CommonResponse<List<Integer>> response = permissionClient.createPath(
                new CreatePathRequest(pathInfos)
        );
        if (!CollectionUtils.isEmpty(response.getData())) {
            log.info("register path info:{}", response.getData());
            return true;
        }
        return false;
    }
}